package com.jake.xfeed.recyclerfeed;

import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class RecyclerViewFeedAdapter<Data> extends RecyclerView.Adapter<FeedViewHolder> {


    @NonNull
    protected IDataSource<Data> mDataSource;
    protected ICardFactory mCardFactory;
    protected CardTypeConverter<Data> mCardTypeConverter;

    public RecyclerViewFeedAdapter(@NonNull IDataSource<Data> dataSource) {
        mDataSource = dataSource;
    }

    public void setCardFactory(ICardFactory factory) {
        this.mCardFactory = factory;
    }

    public void setCardTypeConverter(CardTypeConverter<Data> converter) {
        this.mCardTypeConverter = converter;
    }

    @Override
    public void onViewRecycled(@NonNull FeedViewHolder holder) {
        super.onViewRecycled(holder);
        holder.card.onCardRecycled();
    }


    @NonNull
    @Override
    public FeedViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        BaseCard itemView = null;
        if (this.mCardFactory != null) {
            itemView = this.mCardFactory.getCard(parent.getContext(), viewType);
        }
        RecyclerView.LayoutParams lp = generateDefaultLayoutParams();
        if (itemView == null) {
            itemView = new BaseCard<Data>(parent.getContext()) {
                @Override
                public void onBind(int position, Data data) {
                    //兜底卡不需要实现
                }
            };
            if (lp == null) {
                lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            }
            lp.height = 0;
        }
        if (lp != null) {
            itemView.setLayoutParams(lp);
        }
        return new FeedViewHolder(itemView);
    }

    protected RecyclerView.LayoutParams generateDefaultLayoutParams() {
        return null;
    }

    @Override
    public int getItemViewType(int position) {
        if (mCardTypeConverter != null) {
            Data data = mDataSource.getItem(position);
            if (data != null) {
                return mCardTypeConverter.getType(position, data);
            }
        }
        return super.getItemViewType(position);
    }

    @Override
    public void onBindViewHolder(@NonNull FeedViewHolder holder, int position) {
        Data data = mDataSource.getItem(position);
        holder.card.bind(position, data);
    }

    @Override
    public void onViewAttachedToWindow(@NonNull FeedViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        holder.card.onCardAttachedToWindow();
    }

    @Override
    public void onViewDetachedFromWindow(@NonNull FeedViewHolder holder) {
        super.onViewDetachedFromWindow(holder);
        holder.card.onCardDetachedFromWindow();
    }

    @Override
    public int getItemCount() {
        return mDataSource.getItemCount();
    }


}